package com.example.toutiao.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.toutiao.R;
import com.example.toutiao.db.CartItem;
import com.example.toutiao.db.DatabaseHelper;
import com.example.toutiao.db.Product;

import java.util.List;

//购物车列表
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> {

    private Context context;
    private List<CartItem> cartItems;
    private DatabaseHelper db;

    public CartAdapter(Context context, List<CartItem> cartItems, DatabaseHelper db) {
        this.context = context;
        this.cartItems = cartItems;
        this.db = db;
    }

    public void setData( List<CartItem> cartItems){
        this.cartItems = cartItems;
        notifyDataSetChanged();
    }

    @Override
    public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.cart_item, parent, false);
        return new CartViewHolder(view);
    }

    @Override
    public void onBindViewHolder(CartViewHolder holder, int position) {
        CartItem cartItem = cartItems.get(position);
        Product product = cartItem.getProduct(db);
        if (product != null) {
            holder.tvProductName.setText(product.getName());
            holder.tvProductPrice.setText("价格: ￥" + product.getPrice());
            holder.tvProductQuantity.setText("数量: " + cartItem.getQuantity());
        } else {
            // 如果商品信息为空，设置默认显示内容
            holder.tvProductName.setText("商品信息未找到");
            holder.tvProductPrice.setText("价格: -");
            holder.tvProductQuantity.setText("数量: " + cartItem.getQuantity());
        }
    }

    @Override
    public int getItemCount() {
        return cartItems.size();
    }

    static class CartViewHolder extends RecyclerView.ViewHolder {
        TextView tvProductName, tvProductPrice, tvProductQuantity;

        public CartViewHolder(View itemView) {
            super(itemView);
            tvProductName = itemView.findViewById(R.id.tvProductName);
            tvProductPrice = itemView.findViewById(R.id.tvProductPrice);
            tvProductQuantity = itemView.findViewById(R.id.tvProductQuantity);
        }
    }
}

